/*
 *  $Id$

    Copyright (C) 2008  Nathaniel Waisbrot

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package termint.gui.vt;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Nathaniel Waisbrot
 * Watch for specific VTElements, ignoring the first line and the last two lines
 */
public class VTElementWatcher implements VTChangeListener {
	private final Map<VTElement,List<VTElementListener>> listeners = new HashMap<VTElement,List<VTElementListener>>();
	
	public void addListener(VTElementListener listener, VTElement target) {
		List<VTElementListener> lst = listeners.get(target);
		if (lst == null) {
			lst = new ArrayList<VTElementListener>();
			listeners.put(target, lst);
		}
		lst.add(listener);
	}
	
	@Override
	public void VTChanged(VTChangeEvent event) {
		boolean[] changedLines = event.getChanges();
		VT320 source = event.getSource();
		// first line is messages, last two are status
		for (int y = 1; y < changedLines.length - 2; y++) {
			if (changedLines[y]) {
				for (int x = 0; x < source.getColumns(); x++) {
					VTElement elt = source.elementAt(x, y);
					List <VTElementListener> ls = listeners.get(elt);
					if (ls != null) {
						for (VTElementListener l : ls) {
							l.vtElementSeen(elt, x, y);
						}
					}
				}
			}
		}
	}
}
